﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Hosting;
using Orchard;
using Orchard.Environment.Features;
using dotless.Core.Input;


namespace DotLess.Components
{
    public class OrchardPathResolver : IPathResolver
    {
        private readonly IOrchardServices _services;
        private string _currentFileDirectory;
        private string _currentFilePath;

        public OrchardPathResolver(string currentFilePath, IOrchardServices services) {
            _services = services;
            CurrentFilePath = currentFilePath;
        }


        public string CurrentFilePath {
            get { return _currentFilePath; }
            set {
                _currentFilePath = value;
                _currentFileDirectory = Path.GetDirectoryName(value);
            }
        }

        public string GetFullPath(string filePath) {
            filePath = filePath.Replace('\\', '/').Trim();
            
            if (filePath.StartsWith("~")) {
                filePath = VirtualPathUtility.ToAbsolute(filePath);
            }

            if (filePath.StartsWith("/")) {
                filePath = HostingEnvironment.MapPath(filePath);
            }
            else if (!Path.IsPathRooted(filePath)) {
                var likelyPath = Path.Combine(_currentFileDirectory, filePath); //we will try this first, since it is the most...
                if (new FileInfo(likelyPath).Exists) filePath = likelyPath;
                else {
                    var features = _services.WorkContext.Resolve<IFeatureManager>();
                    var paths = features.GetEnabledFeatures().Select(x => x.Extension.Location + "/" + x.Extension.Id + "/Styles").ToList();

                    var p = filePath;
                    var location = paths.Select(x => new FileInfo(Path.Combine(HostingEnvironment.MapPath(x), p))).FirstOrDefault(x => x.Exists);
                    filePath = location == null ? likelyPath : location.FullName;
                    
                }
            }

            return filePath;
        }
    }

    //This turned out not to be needed, but I don't throw away code.
    //I've seen this used to add ASP.Net theming support to DOtLess
    //public class OrchardLessSource : IFileReader
    //{
    //    public IPathResolver PathResolver { get; set; }

    //    public OrchardLessSource(IPathResolver pathResolver)
    //    {
    //        this.PathResolver = pathResolver;
    //    }

    //    public string GetFileContents(string fileReference)
    //    {
    //        string fileName = this.PathResolver.GetFullPath(fileReference);
    //        string content = File.ReadAllText(fileName);

    //        return content;
    //    }

    //    public bool DoesFileExist(string fileName) {
    //        return new FileInfo(fileName).Exists;
    //    }
    //}
}
